package com.qifn.blog.Controller.Admin;

import com.qifn.blog.Model.Admin;
import com.qifn.blog.Service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Resource
    private AdminService adminService;

    @GetMapping
    public String toLogin(){
        return "admin/login";
    }

    @PostMapping("/login")
    public ModelAndView login(String username, String password, HttpSession session, RedirectAttributes attributes){
        ModelAndView mv = new ModelAndView();
        Admin admin = adminService.CheckAdminLogin(username,password);
        if(admin != null){
            session.setAttribute("admin", admin);
            mv.setViewName("redirect:/admin/index");
        }else {
            attributes.addFlashAttribute("errorLogin","用户名密码错误");
            mv.setViewName("redirect:/admin");
        }
        return mv;
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session){
        ModelAndView mv = new ModelAndView();
        session.removeAttribute("admin");
        mv.setViewName("redirect:/admin");
        return mv;
    }
}
